package com.draw.server.service;

import java.util.List;

import javax.jws.WebMethod;
import javax.jws.WebService;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.draw.core.User;
import com.draw.server.hibernate.HibernateUtil;
import com.draw.webinterface.UserInterface;

@SuppressWarnings("unchecked")
@WebService(targetNamespace = "http://draw.some.com/", serviceName = "UserService", name = "UserService")
public class UserService implements UserInterface {
	private static final Logger logger = LoggerFactory.getLogger(UserService.class);

	@WebMethod
	public List<User> getUserByUsername(String username) {
		Session session = HibernateUtil.getSession();
		String req = "from com.draw.core.User where username like :username";
		Query query = session.createQuery(req);
		query.setString("username", username);
		return query.list();
	}

	@WebMethod
	public User getUser(String username, String password) {
		Session session = HibernateUtil.getSession();
		String req = "from com.draw.core.User where username = :username and password = :password";
		Query query = session.createQuery(req);
		query.setString("username", username);
		query.setString("password", password);
		List<User> l = query.list();
		if (l.size() > 0) {
			return l.get(0);
		} else {
			return null;
		}
	}

	@WebMethod
	public User createUser(User user) {
		logger.info("Creating USER : {}", user);
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.save(user);
		tx.commit();
		return user;
	}

	@WebMethod
	public User updateUser(User user) {
		logger.info("Creating USER : {}", user);
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.update(user);
		tx.commit();
		return user;
	}

	@WebMethod
	public String test() {
		return "Coucou";
	}

	@WebMethod
	public List<User> getAll() {
		Session session = HibernateUtil.getSession();
		return session.createQuery("from com.draw.core.User").list();
	}

	@Override
	public List<User> getAvailableUserToDraw(User user) {
		Session session = HibernateUtil.getSession();
		String req = "from com.draw.core.User where id not in ( select source from com.draw.core.Drawing where destination = :me and done = 0) and id not in ( select destination from com.draw.core.Drawing where source = :me  and done = 0)";
		Query query = session.createQuery(req);
		query.setParameter("me", user);
		return query.list();
	}
}
